/*
 * Copyright 2007 Transmogrify, LLC.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xmog.web.example;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.xmog.web.annotation.CustomBindingErrorHandler;
import com.xmog.web.annotation.Handles;
import com.xmog.web.annotation.UrlParameter;
import com.xmog.web.handler.DataBindingErrorHandler;
import com.xmog.web.view.Forward;
import com.xmog.web.view.View;

/**
 * @author <a href="mailto:maa@xmog.com">Mark Allen</a>
 */
@Singleton
public class SimpleHandler {
	private BackendService backendService;
	private static final Logger log = Logger.getLogger(SimpleHandler.class);

	@Inject
	public SimpleHandler(BackendService backendService) {
		this.backendService = backendService;
	}

	@Handles("/welcome.url")
	public View welcome() {
		log.debug("I'm the welcome.url handler!");
		return new Forward("welcome.jsp");
	}

	@Handles("/display.url")
	public View display(HttpServletRequest request, @UrlParameter("value")
	String value) {
		log.debug("I'm the display.url handler!  Here's a message for you: "
				+ backendService.createMessage(value));
		log.debug("I've also had an HttpServletRequest automatically injected - my session ID is "
				+ request.getSession(true).getId());
		return new Forward("display.jsp");
	}

	@Handles("/error.url")
	// This annotation lets us specify a special handler for binding errors
	// if we'd like to override the global behavior
	@CustomBindingErrorHandler(SpecialErrorHandler.class)
	public void error(@UrlParameter("value")
	Long number) {

	}

	private static final class SpecialErrorHandler implements DataBindingErrorHandler {
		public boolean handle(Map<String, Throwable> errors) {
			return false;
		}
	}
}
